import express from 'express';
import { createConnectionPool } from '../../mysql/index.js';
import axiosInstance from '../../utils/request.js';

const router = express.Router();

// 创建数据库连接池
let connection = await createConnectionPool();
function replaceUndefinedWithNull(values) {
    return values.map(value => value === undefined ? null : value);
}


router.get('/verif_api/user/api/get_order', async (req, res) => {
    const { u_id } = req.query;

    if (!u_id) {
        return res.status(400).send({ error: 'u_id 不存在' });
    }

    try {
        const response = await axiosInstance.post('/api_proxy/user/api/get_order', { data: { page: 1, so: "", type: "", size: 50 } });
        // console.log('Response received:', response.data.data);
        const data = response.data.data;

        const insertPromises = data.map(async order => {
            const {
                id, trade_no, out_trade_no, mchid, name, money, status, endtime,
                r_id, order: orderNo, notice, link, notify_url, return_url, pay_name, pay_type,
                isbudan, terminal, ip, upload_img, upload_remark, pay_img, remarks, loading
            } = order;

            const values = replaceUndefinedWithNull([
                id, u_id, trade_no, out_trade_no, mchid, name, money, status, endtime,
                r_id, orderNo, notice, link, notify_url, return_url, pay_name, pay_type,
                isbudan, terminal, ip, upload_img, upload_remark, pay_img, remarks, loading
            ]);



            const [existingOrders] = await connection.execute('SELECT id FROM order_list WHERE id = ?', [id]);
            if (existingOrders.length > 0) {
                console.log(`Order with id ${id} already exists. Skipping...`);
                return { success: false, message: '重复的订单', order };
            }

            try {
                const [result] = await connection.execute(
                    `INSERT INTO order_list (id, u_id, trade_no, out_trade_no, mchid, name, money, status, endtime, r_id, 
                    \`order\`, notice, link, notify_url, return_url, pay_name, pay_type, isbudan, terminal, ip, 
                    upload_img, upload_remark, pay_img, remarks, loading) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                    values
                );

                if (result.affectedRows === 1) {
                    return { success: true, message: '插入成功', order };
                } else {
                    console.error('Failed to insert the order', order);
                    return { success: false, message: '插入失败', order };
                }
            } catch (insertError) {
                console.error('Error inserting order:', insertError);
                return { success: false, message: '插入失败', order };
            }
        });

        const insertResults = await Promise.all(insertPromises);
        console.log('Insert results:', insertResults);

        const [rows] = await connection.execute('SELECT * FROM order_list WHERE u_id = ?', [u_id]);

        res.status(200).send({
            code: 1,
            message: "操作完成",
            data: rows,
            total: rows.length,
            today_amt: 0,
            today_order_count: 1,
            today_success_count: 0,
            yes_order_count: 0,
            show_img: 0,
            show_remark: 0
        });

    } catch (error) {
        console.error('Error executing query:', error);
        res.status(500).send({ error: 'An error occurred while fetching the order classifications' });
    }
});
export default router;
